<template>
    <!--导入的表的编辑页面-->
    <content-comp class="page-container" >
        <div slot="left">
            <div class="title">
                <span class="text">字段</span>
                <span class="pointer corigin" @click="cancel"><i class="iconfont icon-back-fill corigin ml10" ></i>返回</span>
            </div>
            <fields-com :tableData="fieldsData" :selectedData ="fieldsChecked"
                        @editComplete="editComplete"
                        @checkboxChange="dataSelect"></fields-com>
        </div>
        <div slot="right">
            <div class="title">
                <span class="text">{{tableDataInfo.name}}<!--<i class="el-icon-edit-outline cgray ml10" @click="dialogVisible=true" ></i>--></span>
                <div class="btn-group">
                    <el-button type="primary" size="small"  @click="submitData">保存</el-button>
                    <el-button  type="info"  size="small" @click="cancel">取消</el-button>
                </div>
            </div>
            <div>
                <ATableReady
                    @complete="queryDatabaseCon(tableDataInfo)"
                    :tableFlag="'1'"
                    :tableData ="tableDataCols"
                    :colList="selectedData"
                    style="width: 100%"
                    :recordNumber="recordNumber"
                    :isEditHeader="true"
                    :key="dataTablekey"
                    ref="tableDataCols"
                    @getData ='searchTable'></ATableReady>
            </div>
        </div>
    </content-comp>
</template>

<script>
import ajax from '@api/ajax'
import dataTableCom from './DataTableCom'
import {CUST_TABLE_MAINTAIN, QUERY_FONT_NODE, GET_DATAINFO, QUERY_TMP_DATA_TABLE,QUERY_EXIST_NICKNAME} from '@api/url'
import tree from '@/views/commonView/tree'
import ATableReady from "../../../components/AInitPage/ATable/ATableReady.vue";
import ContentComp from "../../../components/contentComp/contentComp";
import FieldsCom from "../../../components/AInitPage/ATableRadio/fieldsCom";
export default {
    name: 'EditTableData',
    data () {
        return {
            // 弹窗结束
            tableDataCols: [],
            formData: [],
            modelId: '',
            input: '',
            tableLoading: false,
            dataTmp: '',
            listSelect: '',
            listSelectId: '',
            flagTmp: false,
            tableDataInfo: '',
            tableName: '',
            activeName: 'first',
            searchFiled: [],
            dataTablekey: 'tablekey',
            selectedData: [], // 已选字段
            fieldsData:[],
            fieldsChecked:[],
            recordNumber:0,
        }
    },
    components: {
        FieldsCom,
        ATableReady,
        ContentComp,
        dataTableCom
    },
    methods: {
        editComplete(res){//字段修改（字段类型、字段别名修改完成）
            this.queryDatabaseCon (this.tableDataInfo)
        },
        submitData () {
            let conditions = {
                optMode: 'U',
                modelId: this.tableDataInfo.menuId,
                tableId: this.tableDataInfo.tableId,
                modelName: this.tableDataInfo.modelName,
                modelType: '3',
                connId: this.tableDataInfo.connId,
                pcWhere: '',
                pcGrp: '',
                pcOrder: '',
                flag: '0',
                createdBy: 'lzy',
                createdDt: '20210118',
                updatedBy: 'lzy',
                updatedDt: '20200118',
                tdfrs: [{
                    tableId: this.tableDataInfo.tableId,
                    connId: this.tableDataInfo.connId,
                    tableName: this.tableName,
                    alias: this.tableName,
                    tableCnname: this.tableName,
                    tableShowname: this.tableName,
                    srcType: '1',
                    srcLayer: '1',
                    srcSubjec: '1',
                    srcTable: this.tableName,
                    tdfds: []
                }]
            }
            // 在这里筛选一次,但是估计这么写效率不高,但是这个需要以后再改,因为是为了适应公共组件
            let allCol = [];
            (this.fieldsChecked).forEach(seCol => {
                this.dataTmp.forEach(colInfo => {
                    if (colInfo['COLUMN_NAME'] ==seCol) {
                        allCol.push(colInfo)
                    }
                })
            })
            for (var i in allCol) {
                if (allCol[i].COMMENTS == '') {
                    allCol[i].COMMENTS = '未知'
                }
                let col = {
                    fldEnname: allCol[i].COLUMN_NAME,
                    fldShowname: allCol[i].COMMENTS,
                    fldAlias: allCol[i].COLUMN_NAME,
                    fldCnname: allCol[i].COMMENTS,
                    fldType: allCol[i].DATA_TYPE,
                    fldLen: allCol[i].DATA_LENGTH,
                    seqno: allCol[i].COLUMN_ID
                }
                conditions.tdfrs[0].tdfds.push(col)
            }
            ajax.post(CUST_TABLE_MAINTAIN, conditions).then(res => {
                this.cancel()
            }).catch(err => {
                console.error('加载出错！', err)
            }).finally(() => {

            })
        },
        queryDatabaseCon (val) {
            // 传入需要的参数反显数据
            this.modelId = val.menuId
            this.formData = ''
            this.tableDataInfo = val
            let conData = {modelId: val.menuId, idType: '2', connId: val.connId, pageNo: '1', pageSize: '10801'}
            // 根据传递过来的值获取表的所有的字段,并且给已选的字段打上标记
            ajax.post(QUERY_FONT_NODE, conData).then(async res => {
                // 临时存放字段所有信息
                this.dataTmp = res.data;
                let options=[]
                res.data.forEach(col => {
                    options.push({
                        colName:col['COLUMN_NAME'],
                        name: col['COMMENTS']|| col['COLUMN_NAME'],//别名
                        value: col['COLUMN_NAME'],//字段名称
                        dataType:col['COL_TYPE'],//字段类型
                        modelId:this.tableDataInfo.menuId,
                    })
                });
                this.fieldsData=await this.editField(options);
                this.tableName = res.data[0].TABLENAME
                // 查询选中字段
                ajax.post(GET_DATAINFO, {optMode: '1',modelId: val.menuId,pageNo:1,pageSize:15}).then(res => {
                    let tempData = res.data.page.records
                    this.dealTableHeader(Object.keys(tempData[0]));
                    // 初始化查询字段
                    let keys = Object.keys(tempData[0]);
                    this.searchFiled=keys.map(function(key, index) {
                        return {fldName: key, seqNo: index};
                    });
                    this.searchTable()
                })
            })
        },
        async dealTableHeader(tempData=[]){//处理表头数据 ['name','age']
            let fieldsList= this.fieldsData,fieldsOptions=[],checkedOptions=[];//这是表中所有字段
            tempData.forEach(filedName=>{
                let index = fieldsList.findIndex(item=>item.colName==filedName);//找到字段名所在下标
                let curData=fieldsList[index];
                fieldsOptions.push({
                    nickName:curData.name,//别名
                    colName:curData.value,//字段名称
                    modelId:this.tableDataInfo.menuId,
                    colType:curData.dataType,//字段类型
                });
                checkedOptions.push(filedName)
            })
            this.selectedData=await this.editField(fieldsOptions);
            this.fieldsChecked=checkedOptions;
        },
        // 取消操作
        cancel () {
            this.$emit('showSelfData')
        },
        // 选择后调用接口反馈给后台然后反显数据表的内容
        dataSelect (filedsArr=[]) {//val [{别名:'',字段名称:''}]
            this.fieldsChecked=filedsArr.map(item=>item.value);//同时处理一下字段名 在保存时使用
            this.dealTableHeader(this.fieldsChecked);
            //设置左侧表格查询字段
            this.searchFiled=filedsArr.map((item,index)=>{
                return {fldName:item.value, seqNo: index}
            })
            this.searchTable();
        },
        /**
         * 查询表格数据
         * @param params 需要查询的表头
         */
        searchTable(params){
            //整理表格查询入参
             params={...{
                     connId: this.tableDataInfo.connId,
                     modelId:this.modelId,
                     tableLists:[{
                         tableName: this.tableName,
                         seqNo: '1',
                         joinType: '',
                         fldLists:this.searchFiled,//获取查询字段
                     }],//选中的字段列表数据
                     pageNo: '1',//默认第一页
                     pageSize: '15',//默认15条
                 },params}
            this.dataTablekey = tree.UUID(16);// 重置分页
            ajax.post(QUERY_TMP_DATA_TABLE, params).then(res => {
                this.tableDataCols = res.data.records
                this.recordNumber = res.data.recordNumber
            })
        },

        /**修改字段别名和类型
         * {
                nickName:curData.name,//别名
                colName:curData.value,//字段名称
                modelId:this.tableDataInfo.menuId,
                colType:curData.dataType,//字段类型
         * }
         * @param arr
         * @returns {Promise<void>}
         */

        async editField(fieldsArr=[]){
            let tempArr=(await ajax.post(QUERY_EXIST_NICKNAME, {
                optMode: '1', modelId: this.tableDataInfo.menuId, pageNo: 1, pageSize: 15
            })).data;
            fieldsArr.forEach(curData=>{
                let eIndex=tempArr.findIndex(item=>item.colName==curData.colName);//查找修改别名对应下标
                if(eIndex>-1){
                    /*表格使用*/
                    curData['nickName']=tempArr[eIndex].nickName;
                    curData['colType']=tempArr[eIndex].colType;
                    //左侧字段使用
                    curData['name']=tempArr[eIndex].nickName;
                    curData['dataType']=tempArr[eIndex].colType
                }
            });
            return fieldsArr;
        }
    }
}
</script>
<style lang="stylus" scoped>
.page-container{
    padding 0!important
    margin-top 0!important
}
.btn-group{
    display flex
    justify-content flex-end
}

#editTableData
    width 100%
    height 95%
    display flex
    text-align center
    .el-tabs
        height 100%
        .el-tabs__content
            height 90%
            .el-tab-pane
                height 100%
                .el-container
                    height 100%

</style>
